import React,{useEffect,useState} from 'react'
import { List, Skeleton,Pagination,Button, message  } from 'antd';
import {ArticleListApi,ArticleRemoveApi} from '../request/api'
import { useNavigate } from 'react-router-dom';
import moment from 'moment'

export default function ListList() {
  const navigate = useNavigate()
  const [list,setList] = useState([])
  const [update,setUpdate] = useState([])
  const [total,setTotal] = useState(0)
  const [current,setCurrent] = useState(1)
  const [pageSize,setPageSize] = useState(5)


  //请求封装
  const getList = (num)=>{
    ArticleListApi(
      {
        num,
        count:pageSize
      }
    ).then(res=>{
      // console.log(res);
      if(res.errCode === 0){
        let {arr,total,num,count} = res.data
        setList(arr)
        setCurrent(num)
        setTotal(total)
        setPageSize(count)
  
      }
    })
  }

// 请求列表数据 模拟componentDidMount生命周期
useEffect(()=>{
  getList(current)
},[])

// 模拟componentDidUpdate生命周期
useEffect(()=>{
  getList(current)
},[update])

// 分页
const onChange=(pages)=>{
  // setCurrent(pages)
  getList(pages)
}

// 删除功能
const delFn=(id)=>{

ArticleRemoveApi({id}).then(res=>{
  if(res.errCode ===0){
    message.success(res.message)
    // 删除成功之后刷新页面，要么重新请求数据 1.window.reload 2.getList(current)
    setUpdate(update+1)
  }
})
}

  return (
    <div className='list_table' style={{padding:'20px'}}>
        <List
        className="demo-loadmore-list"
        itemLayout="horizontal"
        dataSource={list}
        renderItem={item => (
          <List.Item
            actions={[
            <Button type='primary' onClick={()=>navigate('/edit/'+item.id)}>编辑</Button>,
             <Button type='danger' onClick={()=>delFn(item.id)}>删除</Button>
            ]}
          >
            <Skeleton loading={false}>
              <List.Item.Meta
                title={<a href="!#">{item.title}</a>}
                description={item.subtitle}
              />
              <div>{moment(item.date).format('YYYY-MM-DD hh:mm:ss')}</div>
            </Skeleton>
          </List.Item>
        )}
      />
      <Pagination style={{float:'right',marginTop:'20px'}} onChange={onChange} total={total} current={current} pageSize={pageSize}></Pagination>
    </div>
  )
}
